import 'dart:async';
import 'dart:convert';

import 'package:app/common/colors.dart';
import 'package:app/pages/splash_screen_module/splash_model.dart';
import 'package:app/pages/splash_screen_module/video_splash_screen_page.dart';
import 'package:app/utils/persisten_storage.dart';
import 'package:bruno/bruno.dart';
import 'package:dots_indicator/dots_indicator.dart';
import 'package:flutter/material.dart';

import '../components/gradient_button.dart';
import '../services/address.dart';
import '../services/dio_manager.dart';
import '../utils/db_tool.dart';
import 'bottom_tab_controller.dart';
import 'login_modules/login_view.dart';
import 'package:get/route_manager.dart';

class GuidePage extends StatefulWidget {
  const GuidePage({super.key});

  @override
  State<StatefulWidget> createState() => _GuidePageState();
}

class _GuidePageState extends State<GuidePage> {
  int _index = 0;
  PageController _pageController =
      PageController(initialPage: 0, keepPage: false, viewportFraction: 1);

  var listData = [];
  var _storageListData = []; // 存储本地数据
  List cacheSelectList = []; // 存储需要缓存的数据
  var networkStatus = -1; // -1：没有网络 1：wifi  2：4G


  StepTasksDb _stepTaskDb = StepTasksDb();

  // /// 打开数据库
  // _initDatabase() async {
  //   String path = await _stepTaskDb.initDatabase();
  //   // await File(path).delete();       // 删除表
  //   await _stepTaskDb.open(path); // 打开表
  // }

  /// 获取本地数据
  // Future getStorageData() async {
  //   var data = await _stepTaskDb.getData(type: 'openAD0');
  //   _storageListData = data;
  //   // if(_storageListData.isNotEmpty){
  //   //   var jsonStr = _storageListData[0]['step_listData'];
  //   //   var json = jsonDecode(jsonStr);
  //   //   SplashModel _cacheModel = SplashModel.fromJson(json);
  //   //   model = _cacheModel;
  //   //   print('cacheModel = ${model?.data?.details?[0].url}');
  //   // }
  //   // setState(() {
  //   //
  //   // });// 先赋值一次 以便添加时使用
  //   setState(() {});
  //   return data;
  // }

  /// insert data
  // insertData(var json) async {
  //   // 创建要存储本地的数据
  //   var dataBase = {
  //     'step_listData': jsonEncode(json),
  //   };
  //   // 不为空的话，证明拿到了正常数据，将其存储到要存储的数据参数中
  //   dataBase['assets_listDetails'] = jsonEncode(json);
  //   // 进行本地缓存
  //   var db_res = await _stepTaskDb.insert(StepTasks(
  //       stepListType: 'openAD0',
  //       stepListData: dataBase['step_listData'],
  //       stepDataDetails: dataBase['assets_listDetails']));
  // }

  SplashModel? model;

  // SplashModel? cacheModel;

  requestDataWithAppOpens() async {
    var json = await DioManager().kkRequest(Address.appOpens, method: 'get');

    // getStorageData().then((value) {
    //   // SplashModel model =
    //   //     SplashModel.fromJson(jsonDecode(value[0]['step_listData']));
    //   SplashModel model1 = SplashModel.fromJson(json);
    //   // compareData(model, model1);
    //   // insertData(json);
    //   model = model1;
    //
    //   print(value);
    // });

    // print('_storageListData =========== ${_storageListData}');
    // if(_storageListData.isNotEmpty){
    //   var jsonStr = _storageListData[0]['step_listData'];
    //   var json = jsonDecode(jsonStr);
    //   SplashModel _cacheModel = SplashModel.fromJson(json);
    //   model = _cacheModel;
    //   print('cacheModel = ${model?.data?.details?[0].url}');
    // }
    // else{
    // insertData(json);
    SplashModel _model = SplashModel.fromJson(json);
    model = _model;
    // print('=======================  end ======================= ');
    // }

    setState(() {});
  }

  /// 对比数据

  // compareData(SplashModel dataModel,SplashModel netJsonModel) {
  //   print(
  //       '${dataModel.data?.details?[0].name} == ${netJsonModel.data?.details?[0]
  //           .name}');
  //   if (dataModel.data?.details?[0].name ==
  //       netJsonModel.data?.details?[0].name) {
  //     print('数据相同');
  //     print(
  //         '${dataModel.data?.details?[0].name} == ${netJsonModel.data
  //             ?.details?[0].name}');
  //     if (dataModel.data?.details?[0].name ==
  //         netJsonModel.data?.details?[0].name) {
  //       print('数据不同');
  //       return true;
  //     } else {
  //       print('数据不同');
  //       return false;
  //     }
  //   }
  // }

  @override
  void initState() {
    super.initState();
    // _initDatabase();
    requestDataWithAppOpens();
  }
  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
  }


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Stack(
        alignment: Alignment.bottomCenter,
        children: [
         GestureDetector(
           onTap: (){
             Get.to(VideoSplashScreenPage());
           },
           child:  PageView.builder(
             scrollDirection: Axis.horizontal,
             reverse: false,
             onPageChanged: (dex) {
               setState(() {
                 _index = dex;
               });
             },
             controller: _pageController,
             pageSnapping: true,
             physics: const ClampingScrollPhysics(),
             itemBuilder: (BuildContext context, int index) {
               return Stack(
                 children: [
                   Container(
                     width: double.infinity,
                     height: double.infinity,
                     decoration: BoxDecoration(
                         image: DecorationImage(
                             image: NetworkImage(
                                 '${model?.data?.details?[index].url}'),
                             fit: BoxFit.cover)),
                   ),
                   index+1==model?.data?.details?.length?GestureDetector(
                     child: Align(
                       alignment: Alignment.bottomCenter,
                       child:Container(
                         margin: EdgeInsets.only(bottom: 25),
                         width: 150,
                         height: 40,
                         child: GradientButton(
                           onPressed: (){
                             Get.to(VideoSplashScreenPage());
                           },
                           borderRadius: BorderRadius.all(Radius.circular(20)),
                           child: Text('点击进入'),
                         ),
                       ),),
                     onTap: (){
                       Get.to(VideoSplashScreenPage());
                       // Get.to(LoginView());
                     },
                   ):Container()
                 ],
               );
             },
             itemCount: model?.data?.details?.length??0,
           ),
         ),
          Positioned(
              bottom: 70,
              child: DotsIndicator(
                  mainAxisSize: MainAxisSize.max,
                  mainAxisAlignment: MainAxisAlignment.center,
                  reversed: false,
                  dotsCount: model?.data?.details?.length ?? 1,
                  position: _index.toDouble(),
                  decorator: const DotsDecorator(
                    activeSize: Size.square(12),
                    color: Colors.grey, // Inactive color
                    activeColor: Colors.blueAccent,
                  )))
        ],
      ),
    );
  }
}
